package com.hmall.trade.listener;

import com.hmall.api.client.PayClient;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.trade.constans.MqConstant;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OrderDelayMessageListener {
    @Autowired
    private IOrderService orderService;
    @Autowired
    private PayClient payClient;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstant.DELAY_ORDER_QUEUE_NAME),
            exchange = @Exchange(name = MqConstant.DELAY_EXCHANGE_NAME, delayed = "true"),
            key = MqConstant.DELAY_ORDER_KEY
    ))
    public void orderDelayMessage(Long orderId) {
        //查询本地订单
        Order order = orderService.getById(orderId);
        //检测订单状态，判断是否已支付
        if (order == null || order.getStatus() != 1) {
            return;
        }
        // 未支付，需要查询订单流水状态
        PayOrderDTO payOrder = payClient.queryPayOrderByBizOrderNo(orderId);
        if (payOrder != null &&  payOrder.getStatus() == 3) {
            // 已支付，修改订单状态为已支付
            orderService.markOrderPaySuccess(orderId);
        }else {
            // 未支付，取消订单， 恢复库存
            orderService.cancelOrder(orderId);
        }


    }

}
